// =================================================================
// File: stat.cpp
// Desc: Contains function for printing out the stat of a file
// =================================================================


// =================================================================
// INCLUDES
// =================================================================

#include <ctime>
#include <string>
#include "FSManager.h"
#include "Inode.h"
#include "commands.h"

using namespace std;
// =================================================================
// FUNCTIONS
// =================================================================

// =================================================================
// Name: stat
// Desc: Prints out the i-node information for the file at the given path
// Args: string path - The path of the file to stat
//       FSManager* fsm - pointer to active FSManager object
// =================================================================

void stat(string path, FSManager *fsm) {

    string filename;
    size_t found;
    Inode *node;
    int inode_index;
    bool isDir = false;
    
    if (path[path.length() - 1] == '/') {
        path.erase(path.length()-1, 1);
    }
    
    found = path.find_last_of("/");
    Directory *dir;

    if (found == string::npos) {
        dir = fsm->GetCurrentDirectory();
    } else {
        dir = fsm->ReadDirectory(path.substr(0,found));
    }

    if (dir == NULL) {
        cerr << "Directory does not exist" << endl;
        return;
    }

    filename = path.substr(found+1);

    if ((dir->GetEntry(filename) == -1) && dir->GetEntry(filename + "/") == -1) {
        cerr << "File " << filename << " does not exist" << endl;
        return;
    }
    
    if (dir->GetEntry(filename) != -1){
        inode_index = dir->GetEntry(filename);
    } else {
        inode_index = dir->GetEntry(filename + "/");
        isDir = true;
    }
    
    node = fsm->ReadInode(inode_index);
    struct tm *timeinfo; 
    cout << "File: " << filename << endl;
    cout << "  Directory: ";
    if (isDir == true) cout << "true" << endl;
    else cout << "false" << endl;
    cout << "  Inode: " << inode_index << endl;
    cout << "  Size: " << node->GetSize() << endl;
    cout << "  Blocks: " << node->GetNumBlocks() << endl;
    cout << "  Links: " << node->GetNumLinks() << endl;
    time_t accessed = node->GetAccessed();
    timeinfo = localtime(&accessed);
    cout << "  Accessed: " << asctime(timeinfo);
    time_t modified = node->GetModified();
    timeinfo = localtime(&modified);
    cout << "  Modified: " << asctime(timeinfo);
    time_t changed = node->GetChanged();
    timeinfo = localtime(&changed);
    cout << "  Changed: " << asctime(timeinfo);
    if(dir->GetInodeIndex() != fsm->GetCurrentDirectory()->GetInodeIndex())
    { 
        if (dir != fsm->GetCurrentDirectory())
            delete dir;
    }
}
